function [hFig] = plotdatagrp(data, G, figName, axesTitle, dataScale, fileDir, fileName, showLegend)
%PLOTDATAGRP 按子图绘制数据组
%
% Input Arguments
% # data: m*n矩阵，采样数沿列排列
% # G: 长度为m的向量，同一数值表示相同的组
% # figName: 字符串，图名
% # axesTitle: 字符串，子图标题
% # dataScale: 数值缩放比例，默认为1
% # fileDir: 字符串，保存图片文件路径，默认为空
% # fileName: 字符串，保存图片文件名，默认为空
% # showLegend: 显示包含各组数据均值、标准差、RMS的图例，默认为true
%
% Output Arguments
% # hFig: 图形句柄

if nargin < 8
    showLegend = true;
end
if nargin < 7
    fileName = [];
end
if nargin < 6
    fileDir = [];
end
if nargin < 5
    dataScale = 1;
end

hFig = preparefig(figName);
uniqGrp = unique(G);
[m, n] = roundsqrt(length(uniqGrp));
nCols = size(data, 2);
upLim = nanmax(data(:))*dataScale;
lowLim = nanmin(data(:))*dataScale;
for i = 1:length(uniqGrp)
    grpInd = find(G==uniqGrp(i));
    subplot(m, n, i);
    hLines = plot(data(grpInd, :)*dataScale, '*-');
    ylim([lowLim, upLim]);
    grid on;
    title([axesTitle ' 第' int2str(uniqGrp(i)) '组']);
    if showLegend
        for j = 1:nCols
            hLines(j).DisplayName = ['μ' num2str(nanmean(data(grpInd, j))*dataScale, 2) ...
                'σ' num2str(nanstd(data(grpInd, j))*dataScale, 2)...
                'RMS' num2str(rms(data(grpInd, j))*dataScale, 2)]; % TODO: nanrms
        end
        legend('Location', 'best');
    end
end
if isempty(fileDir)
    if ~isempty(fileName)
        saveas(hFig, fileName)
    end
else
    if isempty(fileName)
        saveas(hFig, [fileDir figName '.png']);
    else
        saveas(hFig, [fileDir fileName]);
    end
end
end